package com.atomscat.lottery.controller.admin;

import com.atomscat.lottery.config.jwt.JwtTokenProvider;
import com.atomscat.lottery.entity.vo.request.AuthRequest;
import com.atomscat.lottery.entity.vo.response.AuthResponse;
import com.atomscat.lottery.entity.vo.response.BaseResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import static com.atomscat.lottery.entity.constant.HeaderConstant.HEADER_PREFIX;


@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final JwtTokenProvider jwtTokenProvider;
    private final ReactiveAuthenticationManager authenticationManager;

    @PostMapping("/user/login")
    public Mono<BaseResponse<AuthResponse>> login(@Valid @RequestBody AuthRequest request) {
        String username = request.getUsername();
        Mono<Authentication> authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, request.getPassword()));
        return authentication.map(jwtTokenProvider::createToken);
    }

    @GetMapping("/captcha/{type}")
    public Mono<Void> captcha(@PathVariable String type, @RequestParam(name = "code") String code, ServerHttpResponse response) {
        return null;
    }

    @GetMapping("/refresh/token")
    public Mono<BaseResponse<AuthResponse>> refreshToken(ServerHttpRequest request) {
        String bearerToken = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(HEADER_PREFIX)) {
            bearerToken = bearerToken.substring(7);
        }
        return Mono.just(jwtTokenProvider.refreshToken(bearerToken));
    }

}